package com.example.other.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.other.domain.Hospital;
import com.example.other.domain.Orders;
import com.example.other.domain.VO.CalendarVO;
import com.example.other.service.CalendarService;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CalendarServiceImpl extends BaseService implements CalendarService {

    private List<Date> getDates() {
        List<Date> dates = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));

        for (int i = 0; i < 30; i++) {

            dates.add(calendar.getTime());
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        return dates;
    }

    @Override
    public List<CalendarVO> getCalendarByHospital(Integer hospitalId) {
        List<CalendarVO> calendarVOList = new ArrayList<>();

        List<Date> dates = getDates();

        Hospital hospital = hospitalMapper.selectById(hospitalId);
        String[] rules = hospital.getRule().split(",");


        for(int i=0;i<dates.size();i++){
            Date date = dates.get(i);
            Integer day = date.getDay();
            Integer total = Integer.parseInt(rules[day]);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String strDate = formatter.format(date);
            if(total!=0){

                QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(Orders::getOrderdate, strDate);
                queryWrapper.lambda().eq(Orders::getHpid, hospitalId);
                List<Orders> orders = ordersMapper.selectList(queryWrapper);

                Integer remaining = total-orders.size();

                CalendarVO calendarVO = new CalendarVO();
                calendarVO.setYear(strDate.substring(0,4));
                calendarVO.setMonth(strDate.substring(5,7));
                calendarVO.setDay(strDate.substring(8,10));
                calendarVO.setWeek(String.valueOf(day));
                calendarVO.setTotalAmount(total);
                calendarVO.setRemainingAmount(remaining);
                calendarVOList.add(calendarVO);

            }else {
                CalendarVO calendarVO = new CalendarVO();
                calendarVO.setYear(strDate.substring(0,4));
                calendarVO.setMonth(strDate.substring(5,7));
                calendarVO.setDay(strDate.substring(8,10));
                calendarVO.setWeek(String.valueOf(day));
                calendarVO.setTotalAmount(0);
                calendarVO.setRemainingAmount(0);
                calendarVOList.add(calendarVO);
            }

        }

        return calendarVOList;
    }
}
